﻿using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using Newtonsoft.Json;
using BLL;
using Model.TempClass;

namespace FlowMvc.Controllers
{
    public class HomeController : Controller
    {
        SysProcessBLL bll = new SysProcessBLL();
        /// <summary>
        /// 流程步骤设计首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.FlowID = Request.QueryString["FlowID"];
            ViewBag.lblText = Request.QueryString["FlowName"];
            return View();
        }
        /// <summary>
        /// 获取步骤数据 
        /// </summary>
        /// <returns></returns>
        public ActionResult AjaxData()
        {
            int flow = Convert.ToInt32(Request.QueryString["FlowID"]);
            using (FlowDBEntities db = new FlowDBEntities())
            {
                List<SysProcess> list = bll.GetList(flow); //db.SysProcess.Where(item => item.flow_id == flow).Select(item => item).ToList();
                List<SysRelation> listRe = bll.GetRelationAll(flow);// db.SysRelation.Select(item => item).ToList();
                List<FlowModel> listFlow = new List<FlowModel>();
                StringBuilder str = new StringBuilder();
                //str.Append("{");
                foreach (var item in list)
                {
                    FlowModel model = new FlowModel();
                    model.flow_id = item.flow_id.ToString();
                    model.icon = item.icon;
                    model.id = item.id.ToString();
                    model.process_name = item.process_name;
                    model.style = item.style;
                    string process_to = "";
                    foreach (var m in listRe.Where(i => i.process_id == item.id))
                    {

                        process_to = process_to == "" ? m.process_toid + "" : process_to + "," + m.process_toid;
                    }
                    model.process_to = process_to == "" ? "0" : process_to;
                    //listFlow.Add(model);
                    string json = JsonConvert.SerializeObject(model);
                    if (str.Length > 5)
                    {
                        str.Append(",");
                    }
                    str.Append("\"" + model.id + "\":" + json);
                }
                //str.Append("}");
                return Content("{\"list\":{" + str.Replace("null", "\"\"").ToString() + "},\"total\":" + list.Count + "}");
            }
        }
        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="Flow"></param>
        /// <returns></returns>
        public ActionResult AddFlow(FlowModel Flow)
        {
            try
            {
                if (bll.Add(Flow) > 0)
                {
                    return Json(new { statu = 1 }, JsonRequestBehavior.AllowGet);
                }
                //using (FlowDBEntities db = new FlowDBEntities())
                //{
                //    SysProcess proModel = new SysProcess();
                //    proModel.flow_id = int.Parse(Flow.flow_id);
                //    proModel.icon = Flow.icon;
                //    proModel.process_name = Flow.process_name;
                //    proModel.style = Flow.style;
                //    db.SysProcess.Add(proModel);
                //    db.SaveChanges();
                //    return Json(new { statu = 1 }, JsonRequestBehavior.AllowGet);
                //}
            }
            catch (Exception ex)
            {

            }
            return Json(new { statu = 0 }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="flow"></param>
        /// <returns></returns>
        public ActionResult DeleteFlow(FlowModel flow)
        {
            try
            {
                if (bll.DeleteProcess(int.Parse(flow.id)) > 0)
                {
                    return Json(new { statu = 1 }, JsonRequestBehavior.AllowGet);
                }
                //using (FlowDBEntities db = new FlowDBEntities())
                //{
                //    int id = int.Parse(flow.id);
                //    SysProcess model = db.SysProcess.Where(item => item.id == id).FirstOrDefault();
                //    if (model != null)
                //    {
                //        db.SysProcess.Remove(model);
                //        db.SaveChanges();
                //    }
                //    db.SaveChanges();

                //}
            }
            catch (Exception ex)
            {
            }
            return Json(new { statu = 0 }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存流程
        /// </summary>
        /// <param name="FlowInfo"></param>
        /// <returns></returns>
        public ActionResult AjaxSaveProcess(string FlowInfo)
        {
            try
            {
                int flow = Convert.ToInt32(Request.QueryString["FlowID"]);

                List<FlowInfoModel> model = JsonConvert.DeserializeObject<List<FlowInfoModel>>(FlowInfo);
                int result = 0;
                //using (FlowDBEntities db = new FlowDBEntities())
                //{
                List<SysProcess> listPro = bll.GetList(flow);//db.SysProcess.Where(i => i.flow_id == flow).Select(i => i).ToList();
                foreach (var item in listPro)
                {
                    var info = model.Where(j => j.process_id == item.id).FirstOrDefault();
                    if (info != null)
                    {

                        string styleStr = "";


                        string[] style = item.style.Split(';');
                        styleStr += "left:" + info.left + "px;" + "top:" + info.top + "px;";
                        for (int i = 0; i < style.Length; i++)
                        {
                            if (!style[i].Contains("left") && !style[i].Contains("top") && !string.IsNullOrWhiteSpace(style[i]))
                            {
                                styleStr += style[i] + ";";
                            }
                        }
                        item.style = styleStr;
                        //更新位置信息
                        if (bll.EditStyle(item) > 0)
                        {
                            //List<SysRelation> listRelation = bll.GetRelation(info.process_id); //db.SysRelation.Where(i => i.process_id == info.process_id).Select(i => i).ToList();
                            //db.SysRelation.RemoveRange(listRelation);
                            result += bll.DeleteRelationAll(info.process_id);
                            for (int i = 0; i < info.process_to.Length; i++)
                            {
                                SysRelation relation = new SysRelation();
                                relation.process_id = info.process_id;
                                relation.process_toid = info.process_to[i];
                                relation.flowID = flow;
                                result += bll.AddRelation(relation);
                                //db.SysRelation.Add(relation);

                            }
                        }
                    }
                    //添加新步骤
                    //else {
                    //    SysProcess pro = new SysProcess();
                    //    pro.flow_id = 1;
                    //    pro.process_name = "";
                    //    string styleStr = "";
                    //    string[] style = item.style.Split(';');
                    //    styleStr += "left:" + info.left + "px;" + "top:" + info.top + "px;";
                    //    for (int i = 0; i < style.Length; i++)
                    //    {
                    //        if (!style[i].Contains("left") && !style[i].Contains("top") && !string.IsNullOrWhiteSpace(style[i]))
                    //        {
                    //            styleStr += style[i] + ";";
                    //        }
                    //    }
                    //    pro.style = styleStr;
                    //}
                }
                // = db.SaveChanges();
                // }
                if (result > 0)
                {
                    return Json(new { statu = 1 }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {
                return Json(new { statu = 0 }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { statu = 0 }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 属性视图
        /// </summary>
        /// <returns></returns>
        public ActionResult AttributeView()
        {
            return View();
        }
        /// <summary>
        /// 获取OA审批按钮信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AjaxGetBtn()
        {
            try
            {
                List<SelectModel> list = null;
                list = bll.GetBtn();
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取OA操作按钮信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AjaxGetOperation()
        {
            try
            {
                List<SelectModel> list = null;
                list = bll.GetOperation();
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取OA审批角色信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AjaxGetRole()
        {
            try
            {
                string flowid = Request.QueryString["FlowID"];
                List<SelectModel> list = null;
                list = bll.GetRole(flowid);
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取步骤详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AjaxGetDetail(int id)
        {
            try
            {
                SysProcess model = bll.GetDateil(id);
                return Json(new { statu = 1, data = model }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new { statu = 0, data = "" }, JsonRequestBehavior.AllowGet);

            }


        }
        /// <summary>
        /// 获取审批意见
        /// </summary>
        /// <returns></returns>
        public ActionResult AjaxGetItem()
        {
            try
            {
                List<SelectModel> list = null;
                list = bll.GetItem();
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取当前流程可退回的步骤
        /// </summary>
        /// <returns></returns>
        public ActionResult AjaxGetBackProcess()
        {
            try
            {
                string flowid = Request.QueryString["FlowID"];
                if (!string.IsNullOrWhiteSpace(flowid))
                {
                    int id = Convert.ToInt32(flowid);
                    List<SelectModel> list = null;
                    list = bll.GetBackProcess(id);
                    return Json(list, JsonRequestBehavior.AllowGet);
                }
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 保存步骤详情
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AjaxSaveDetail(SysProcess entity)
        {
            try
            {

                if (bll.SaveDetail(entity) > 0)
                {
                    return Json(new { statu = 1 }, JsonRequestBehavior.AllowGet);
                }

                //using (FlowDBEntities db = new FlowDBEntities())
                //{
                //    SysProcess model = db.SysProcess.Where(i => i.id == entity.id).FirstOrDefault();
                //    if (model != null)
                //    {
                //        model.OperationID = entity.OperationID;
                //        model.Other = entity.Other;
                //        model.process_name = entity.process_name;
                //        model.RoleID = entity.RoleID;
                //        model.SuggesItem = entity.SuggesItem;
                //        model.SuggesLabel = entity.SuggesLabel;
                //        model.Approval = entity.Approval;
                //        model.Atten = entity.Atten;
                //        model.BackID = entity.BackID;
                //        model.Buttons = entity.Buttons;
                //        model.Condition = entity.Condition;
                //        model.FunctionType = entity.FunctionType;
                //        model.icon = entity.icon;
                //        model.UpdateTime = DateTime.Now;
                //    }
                //    if (db.SaveChanges() > 0)
                //    {
                //        return Json(new { statu = 1 }, JsonRequestBehavior.AllowGet);
                //    }
                //}
            }
            catch (Exception)
            {

                throw;
            }
            return Json(new { statu = 0 }, JsonRequestBehavior.AllowGet);

        }
    }
    /// <summary>
    /// 返回数据
    /// </summary>
    //public class FlowModel
    //{
    //    public string id { get; set; }
    //    public string flow_id { get; set; }
    //    public string icon { get; set; }
    //    public string process_name { get; set; }
    //    public string style { get; set; }
    //    public string process_to { get; set; }
    //}
    //public class FlowInfoModel
    //{
    //    public int process_id { get; set; }
    //    public string left { get; set; }
    //    public string top { get; set; }
    //    public int[] process_to { get; set; }
    //}
    //public class SelectModel
    //{
    //    public string Id { get; set; }
    //    public string Text { get; set; }
    //}
}